import { onMounted, onUnmounted, ref } from 'vue';

/**
 * 就是一个很普通的函数
 * 在 setup 函数中，onUnmounted | onMounted 等钩子函数都会统一执行
 * ref 等，就是单独的能够响应的操作
 * @param {Object} opts 配置项
 * @param {string} opts.src script 地址
 */
export function useScript (opts) {
  const isLoading = ref(true);
  const error = ref(false);
  const success = ref(false);
  let script;

  const promise = new Promise((resolve, reject) => {
    onMounted(() => {
      script = document.createElement('script');
      script.type = 'text/javascript';
      script.onload = function () {
        isLoading.value = false;
        success.value = true;
        error.value = false;
        resolve('');
      };

      script.onerror = function (err) {
        isLoading.value = false;
        success.value = false;
        error.value = true;
        reject(err);
      };

      script.src = opts.src;
      document.head.appendChild(script);
    });
  });

  onUnmounted(() => {
    script && script.remove();
  });

  return {
    isLoading,
    error,
    success,
    toPromise: () => promise,
  };
}
